package corewarsxxi.gui;

import corewarsxxi.logic.Core;
import corewarsxxi.logic.IObserver;
import corewarsxxi.logic.MemoryCell;
import corewarsxxi.logic.Warrior;
import java.awt.Color;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

/**
 *
 * @author ei10139
 */
public class Canvas extends JPanel implements IObserver
{
    CanvasMemoryCell cmf [] = new CanvasMemoryCell[Core.getInstance().getSize()];
    private Debugger deb;

    Canvas(Debugger deb)
    {
        super();
        this.deb = deb;
        this.setBackground(Color.lightGray);
        this.setBorder(new LineBorder(Color.lightGray, 1, true));
        GroupLayout layout = new GroupLayout(Canvas.this);
        layout.setAutoCreateGaps(false);
        layout.setAutoCreateContainerGaps(false);

        ParallelGroup groupHLabels = layout.createParallelGroup();
        SequentialGroup groupVLabels = layout.createSequentialGroup();
        int canvasMCid = 0;
        int coreSize = Core.getInstance().getSize();
        for(int i = 0; i < 54; ++i)
        {
            SequentialGroup groupHLabelsLine = layout.createSequentialGroup();
            ParallelGroup groupVLabelsLine = layout.createParallelGroup();
            for(int j = 0; j < 150 && canvasMCid < coreSize; ++j, ++canvasMCid)
            {
                cmf[canvasMCid] = new CanvasMemoryCell(this);

                groupHLabelsLine.addGroup(
                        layout.createSequentialGroup()
                            .addComponent(cmf[canvasMCid])
                        );
                groupVLabelsLine.addGroup(
                        layout.createParallelGroup()
                            .addComponent(cmf[canvasMCid])
                        );
                layout.linkSize(cmf[canvasMCid]);
            }
            groupHLabels.addGroup(groupHLabelsLine);
            groupVLabels.addGroup(groupVLabelsLine);
        }

        layout.setHorizontalGroup(groupHLabels);
        layout.setVerticalGroup(groupVLabels);

        Canvas.this.setLayout(layout);
    }

    public void notifyObs(MemoryCell obs, int offset, Warrior w)
    {
        if(offset < 0 || obs == null)
            return;

        cmf[offset].setBackground(w.getColor());
    }

    protected boolean updateDebuggerOffset(CanvasMemoryCell cmc) {
        for(int i = 0; i < cmf.length; ++i)
            if(cmc.equals(cmf[i]))
                return deb.updateDebuggerOffset(i);
        
        return false;
    }

    void reset() {
        int coreSize = Core.getInstance().getSize();
        int canvasMCid = 0;
        for(int i = 0; i < 54; ++i)
        {
            for(int j = 0; j < 150 && canvasMCid < coreSize; ++j, ++canvasMCid)
            {
                cmf[canvasMCid].setBackground(Color.black);
            }
        }
    }
}
